package com.lmuse.xmr.foodspotting.ui.main;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.lmuse.xmr.foodspotting.BaseActivity;
import com.lmuse.xmr.foodspotting.FoodApplication;
import com.lmuse.xmr.foodspotting.R;
import com.lmuse.xmr.foodspotting.constants.App;
import com.lmuse.xmr.foodspotting.constants.Permission;
import com.lmuse.xmr.foodspotting.db.Contract;
import com.lmuse.xmr.foodspotting.db.UserPresenterImpl;
import com.lmuse.xmr.foodspotting.model.User;
import com.lmuse.xmr.foodspotting.ui.classify.ClassifyFragment;
import com.lmuse.xmr.foodspotting.ui.discover.DiscoverFragment;
import com.lmuse.xmr.foodspotting.ui.homepage.HomepageFragment;
import com.lmuse.xmr.foodspotting.ui.upload.UploadActivity;
import com.lmuse.xmr.foodspotting.ui.upload.UploadFragment;
import com.lmuse.xmr.foodspotting.ui.userpage.UserPageFragment;
import com.lmuse.xmr.foodspotting.util.SDCardUtil;
import com.lmuse.xmr.foodspotting.util.permission.PermissionListener;
import com.lmuse.xmr.foodspotting.util.permission.PermissionManager;
import com.sendtion.xrichtext.RichTextEditor;

import java.util.List;

import cn.bmob.v3.exception.BmobException;

public class MainActivity extends BaseActivity implements RichTextEditor.OnDeleteImageListener, Contract.UserView{

    private FoodApplication foodApplication;
    private PermissionManager helper;

    private FragmentManager fragmentManager;
    private ConstraintLayout framelayout;
    private Fragment homepageFragment;
    private Fragment classifyFragment;
    private Fragment uploadFragment;
    private Fragment discoverFragment;
    private Fragment userPageFragment;

    private RadioGroup tab;
    private RadioButton homepageTab;
    private RadioButton classifyTab;
    private RadioButton uploadTab;
    private RadioButton discoverTab;
    private RadioButton userTab;

    private Contract.UserPresenter userPresenter;
    private User user;
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userPresenter = new UserPresenterImpl(this);
        initView();
        initDefaultFragment();
        onPermission();
        userPresenter.getUserInfoCache();
    }

    private void initView() {

        foodApplication = (FoodApplication) this.getApplicationContext();
        foodApplication.setMainFlag(App.ON_HOMEPAGE);
        fragmentManager = getSupportFragmentManager();

        framelayout = (ConstraintLayout) findViewById(R.id.main_fragment_layout);
        homepageFragment = new HomepageFragment();
        classifyFragment = new ClassifyFragment();
        uploadFragment = new UploadFragment();
        discoverFragment = new DiscoverFragment();
        userPageFragment = new UserPageFragment();

        tab = (RadioGroup) findViewById(R.id.rg_tab);
        homepageTab = (RadioButton) findViewById(R.id.rb_tab_homepage);
        classifyTab = (RadioButton) findViewById(R.id.rb_tab_classify);
        uploadTab = (RadioButton) findViewById(R.id.rb_tab_upload);
        discoverTab = (RadioButton) findViewById(R.id.rb_tab_discover);
        userTab = (RadioButton) findViewById(R.id.rb_tab_user_page);

        homepageTab.setOnClickListener(new ButtonClickListener());
        classifyTab.setOnClickListener(new ButtonClickListener());
        uploadTab.setOnClickListener(new ButtonClickListener());
        discoverTab.setOnClickListener(new ButtonClickListener());
        userTab.setOnClickListener(new ButtonClickListener());
    }

    //初始化默认fragment的加载
    private void initDefaultFragment() {
        FragmentTransaction mainTransaction = fragmentManager.beginTransaction();
        mainTransaction.replace(R.id.main_fragment_layout, homepageFragment);
        mainTransaction.commit();
    }

    class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rb_tab_homepage:
                    goToHomepage();
                    foodApplication.setMainFlag(App.ON_HOMEPAGE);
                    break;
                case R.id.rb_tab_classify:
                    gotoClassify();
                    foodApplication.setMainFlag(App.ON_CLASSIFY);
                    break;
                case R.id.rb_tab_upload:
//                    if (user != null) {
                        Intent intent = new Intent(MainActivity.this, UploadActivity.class);
                        startActivity(intent);
//                    }else {
//                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                        startActivity(intent);
//                    }
//                    gotoUpload();
//                    foodApplication.setMainFlag(App.ON_UPLOAD);
                    break;
                case R.id.rb_tab_discover:
//                    if (user != null) {
                        gotoDiscover();
                        foodApplication.setMainFlag(App.ON_DISCOVER);
//                    }else {
//                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                        startActivity(intent);
//                    }
                    break;
                case R.id.rb_tab_user_page:
                    gotoUserPage();
                    foodApplication.setMainFlag(App.ON_USER_PAGE);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        switch (foodApplication.getMainFlag()) {
            case App.ON_HOMEPAGE:
                goToHomepage();
                tab.check(R.id.rb_tab_homepage);
                break;
            case App.ON_CLASSIFY:
                gotoClassify();
                tab.check(R.id.rb_tab_classify);
                break;
            case App.ON_UPLOAD:
//                gotoUpload();
                break;
            case App.ON_DISCOVER:
                gotoDiscover();
                tab.check(R.id.rb_tab_discover);
                break;
            case App.ON_USER_PAGE:
                gotoUserPage();
                tab.check(R.id.rb_tab_user_page);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDeleteImage(String s) {
        boolean isOK = SDCardUtil.deleteFile(s);
        if (isOK){
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
        }
    }

    void goToHomepage() {
        FragmentTransaction homepageTransaction = fragmentManager.beginTransaction();
        homepageTransaction.replace(R.id.main_fragment_layout, homepageFragment);
        homepageTransaction.commit();
    }

    void gotoClassify() {
        FragmentTransaction classifyTransaction = fragmentManager.beginTransaction();
        classifyTransaction.replace(R.id.main_fragment_layout, classifyFragment);
        classifyTransaction.commit();
    }

    void gotoUpload() {
        FragmentTransaction uploadTransaction = fragmentManager.beginTransaction();
        uploadTransaction.replace(R.id.main_fragment_layout, uploadFragment);
        uploadTransaction.commit();
    }

    void gotoDiscover() {
        FragmentTransaction discoverTransaction = fragmentManager.beginTransaction();
        discoverTransaction.replace(R.id.main_fragment_layout, discoverFragment);
        discoverTransaction.commit();
    }

    void gotoUserPage() {
        FragmentTransaction userPageTransaction = fragmentManager.beginTransaction();
        userPageTransaction.replace(R.id.main_fragment_layout, userPageFragment);
        userPageTransaction.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    void onPermission() {
        helper = PermissionManager.with(MainActivity.this)
                //添加权限请求码
                .addRequestCode(Permission.REQUEST_CODE_INTERNET)
                //设置权限，可以添加多个权限
                .permissions(Manifest.permission.INTERNET)
                //设置权限监听器
                .setPermissionsListener(new PermissionListener() {

                    @Override
                    public void onGranted() {
                        //当权限被授予时调用
//                        Toast.makeText(MainActivity.this, "网络权限已授权",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onDenied() {
                        //用户拒绝该权限时调用
                        Toast.makeText(MainActivity.this, "网络权限被拒绝",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onShowRationale(String[] permissions) {
                        //当用户拒绝某权限时并点击`不再提醒`的按钮时，下次应用再请求该权限时，需要给出合适的响应（比如,给个展示对话框来解释应用为什么需要该权限）

                        AlertDialog permissionDialog = new AlertDialog
                                .Builder(MainActivity.this)
                                .setTitle("需要网络权限联网获取信息")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //必须调用该`setIsPositive(true)`方法
                                        helper.setIsPositive(true);
                                        helper.request();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create();
                        permissionDialog.show();
                    }
                })
                //请求权限
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Permission.REQUEST_CODE_INTERNET:
                helper.onPermissionResult(permissions, grantResults);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// && event.getAction() == KeyEvent.ACTION_DOWN
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                myExit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void myExit() {
        Intent intent = new Intent();
        intent.setAction("ExitApp");
        this.sendBroadcast(intent);
        super.finish();
    }

    @Override
    public void onSignUpSuccess(User user) {

    }

    @Override
    public void onSignUpFailed(String msg) {

    }

    @Override
    public void onSignInSuccess(User user) {

    }

    @Override
    public void onSignInFailed(String msg) {

    }

    @Override
    public void onUserInfoCache(User user) {

        if (user != null) {
            this.user = user;
        }
    }

    @Override
    public void onUpdateUserSuccess() {

    }

    @Override
    public void onUpdateUserFailed(String msg) {

    }

    @Override
    public void onRequestEmailVerifyResult(BmobException e) {

    }

    @Override
    public void onResetPasswordByEmailResult(BmobException e) {

    }

    @Override
    public void onQueryUserByIdSuccess(User user) {

    }

    @Override
    public void onQueryUserByIdFailed(String msg) {

    }

    @Override
    public void onQueryUserAmountSuccess(int size) {

    }

    @Override
    public void onQueryUserAmountFailed(String msg) {

    }

    @Override
    public void onQueryByKeySuccess(List<User> userList) {

    }

    @Override
    public void onQueryByKeyFailed(String msg) {

    }
}
